package com.stockz.ui.swing.watchlist.widget;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.Date;
import java.util.List;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.stockz.core.manager.ImportExportManager;
import com.stockz.ui.swing.core.MainFrame;
import com.stockz.ui.swing.widget.JMenuItem;
import com.stockz.watchlist.manager.WatchListManager;
import com.stockz.watchlist.model.WatchList;
import com.stockz.watchlist.model.WatchListEntry;

@Component
public class ImportWatchListMenuItem extends JMenuItem  implements ActionListener{
	private static final long serialVersionUID = -652538317657462610L;

	@Autowired
	private ImportExportManager importExportManager;
	@Autowired
	private WatchListManager watchListManager;
	
	public ImportWatchListMenuItem() {
		super("Import All");
		addActionListener(this);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void actionPerformed(ActionEvent e) {
		 JFileChooser chooser = new JFileChooser();
		 FileFilter filter = new FileFilter(){
			@Override
			public boolean accept(File pathname) {
					return pathname.getName().endsWith("xml");
			}
			
			@Override
			public String getDescription() {
				return "xml";
			}
		 };

		 chooser.setFileFilter(filter);
		 if(chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION){
			 try {
				 List<WatchList> watchListList = (List<WatchList>)importExportManager.importData(chooser.getSelectedFile().getAbsolutePath());
				 if(watchListList != null && !watchListList.isEmpty()){
					 for(WatchList watchList : watchListList){
						 watchList.setId(null);
						 watchListManager.create(watchList);
						 if(watchList.getEntryList() != null && !watchList.getEntryList().isEmpty()){
							 for(WatchListEntry entry : watchList.getEntryList()){
								 entry.setId(null);
								 if(entry.getInspectionDate() == null){
									 entry.setInspectionDate(new Date());
								 }
								 entry.setWatchList(watchList);
								 watchListManager.create(entry);
							 }
						 }
					 }
				 }
			 }catch(Exception e1){
				 e1.printStackTrace();
					JOptionPane.showMessageDialog(MainFrame.getInstance(),
						    e1.getMessage(),
						    "Error",
						    JOptionPane.ERROR_MESSAGE);
			 }
		 }
		 
	}
	
}
